package group

import (
	"context"

	"gitee.com/gao-deguang/easy-chat/apps/social/api/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/social/api/internal/types"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/social"
	"gitee.com/gao-deguang/easy-chat/apps/user/rpc/user"
	"gitee.com/gao-deguang/easy-chat/pkg/ctxdata"
	"gitee.com/gao-deguang/easy-chat/pkg/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type GroupPutInHandleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 入群申请处理
func NewGroupPutInHandleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GroupPutInHandleLogic {
	return &GroupPutInHandleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GroupPutInHandleLogic) GroupPutInHandle(req *types.GroupPutInHandleReq) (resp *types.GroupPutInHandleResp, err error) {
	// todo: add your logic here and delete this line
	hderid := ctxdata.GetUID(l.ctx)
	hder, err := l.svcCtx.UserRpc.FindUser(l.ctx, &user.FindUserReq{
		Ids: []string{hderid},
	})
	if err != nil {
		return &types.GroupPutInHandleResp{}, err
	}
	if len(hder.Users) != 1 {
		return &types.GroupPutInHandleResp{}, xerr.NewDBErr()
	}
	_, err = l.svcCtx.Social.GroupPutInHandle(l.ctx, &social.GroupPutInHandleReq{
		GroupReqId:    req.GroupReqId,
		GroupId:       req.GroupId,
		HandleUid:     hderid,
		HandleResult:  req.HandleResult,
		Username:      hder.Users[0].Nickname,
		UserAvatarUrl: hder.Users[0].Avatar,
	})
	if err != nil {
		return nil, err
	}

	//todo:入群成功后创建会话
	//申请的时候看看自己是否入群了(需要在添加对应的返回值)
	//是否创建了会话，若没有，则创建
	//调用IMRPC服务
	return
}
